package org.port.weather.ui;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.port.R;
import org.port.util.Log;
import org.port.util.Util;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.text.Editable;
import android.text.method.KeyListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

public class AddressPopup extends PopupWindow implements OnClickListener,
		OnItemSelectedListener {
	public static final String TAG = "AddressPopup";
	private Context context;
	private Spinner spinSido;
	private Spinner spinGugun;
	private Spinner spinDong;
	private Button btnConfirm;
	private Button btnCancel;
	private NodeList nListDong;
	private String gridData;
	public boolean isConfirm = false;
	public String address = "";

	public AddressPopup(Context context, View contentView, int width,
			int height, boolean focusable) {
		super(contentView, width, height, focusable);
		// TODO Auto-generated constructor stub
		this.context = context;
		spinSido = (Spinner) contentView.findViewById(R.id.spin_sido);
		spinGugun = (Spinner) contentView.findViewById(R.id.spin_gugun);
		spinDong = (Spinner) contentView.findViewById(R.id.spin_dong);
		btnConfirm = (Button) contentView.findViewById(R.id.btn_confirm);
		btnCancel = (Button) contentView.findViewById(R.id.btn_cancel);
		spinSido.setOnItemSelectedListener(this);
		spinGugun.setOnItemSelectedListener(this);
		spinDong.setOnItemSelectedListener(this);
		btnConfirm.setOnClickListener(this);
		btnCancel.setOnClickListener(this);

	}

	@Override
	public void showAsDropDown(View anchor, int xoff, int yoff) {
		// TODO Auto-generated method stub
		super.showAsDropDown(anchor, xoff, yoff);
	}

	@Override
	public void showAsDropDown(View anchor) {
		// TODO Auto-generated method stub
		super.showAsDropDown(anchor);
	}

	@Override
	public void showAtLocation(View parent, int gravity, int x, int y) {
		// TODO Auto-generated method stub
		super.showAtLocation(parent, gravity, x, y);
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
		// TODO Auto-generated method stub
		switch (parent.getId()) {
		case R.id.spin_sido:
			Log.d(TAG, "sido select");
			ArrayAdapter<String> adapterGugun = new ArrayAdapter<String>(
					context, android.R.layout.simple_spinner_item,
					getGugunData(spinSido.getSelectedItemPosition()));
			spinGugun.setAdapter(adapterGugun);
			spinGugun.invalidate();
			break;
		case R.id.spin_gugun:
			Log.d(TAG, "gugun select");
			ArrayAdapter<String> adapterDong = new ArrayAdapter<String>(
					context, android.R.layout.simple_spinner_item, getDongData(
							spinSido.getSelectedItemPosition(),
							spinGugun.getSelectedItemPosition()));
			spinDong.setAdapter(adapterDong);
			spinDong.invalidate();
			break;
		case R.id.spin_dong:
			Log.d(TAG, "dong select");
			getGridData(spinDong.getSelectedItemPosition());
			Log.d(TAG, gridData);
			break;

		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setOutsideTouchable(boolean touchable) {
		// TODO Auto-generated method stub
		Log.d(TAG, "setOutsideTouchable()");
		super.setOutsideTouchable(touchable);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_confirm:
			isConfirm = true;
			dismiss();
			break;
		case R.id.btn_cancel:
			isConfirm = false;
			dismiss();
			break;

		default:
			break;
		}
	}

	private void getGridData(int pos) {
		gridData = nListDong.item(pos).getAttributes().getNamedItem("grid")
				.getTextContent();
	}

	public String getGridData() {
		return gridData;
	}

	private ArrayList<String> getGugunData(int pos) {
		ArrayList<String> list = new ArrayList<String>();
		AssetManager am = context.getAssets();
		Document doc = null;
		try {
			doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(am.open(getFileName(pos)));
			XPath xPath = XPathFactory.newInstance().newXPath();
			NodeList nList = (NodeList) xPath.evaluate("//gugun", doc,
					XPathConstants.NODESET);
			for (int i = 0; i < nList.getLength(); i++) {
				Node n = nList.item(i);
				String name = n.getAttributes().getNamedItem("name")
						.getTextContent();
				System.out.println(name);
				list.add(name);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DOMException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}

	private ArrayList<String> getDongData(int filePos, int gugunPos) {
		ArrayList<String> list = new ArrayList<String>();
		AssetManager am = context.getAssets();
		try {
			Document doc = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder().parse(am.open(getFileName(filePos)));
			XPath xPath = XPathFactory.newInstance().newXPath();
			nListDong = (NodeList) xPath.evaluate("//gugun[@name='"
					+ spinGugun.getAdapter().getItem(gugunPos) + "']/dong",
					doc, XPathConstants.NODESET);
			for (int i = 0; i < nListDong.getLength(); i++) {
				Node n = nListDong.item(i);
				String name = n.getAttributes().getNamedItem("name")
						.getTextContent();
				System.out.println(name);
				list.add(name);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void dismiss() {
		// TODO Auto-generated method stub
		SharedPreferences preferences = context.getSharedPreferences(
				context.getString(R.string.app_name), Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString(Util.LAST_GRID, gridData);
		editor.putString(Util.LAST_TOWN,
				spinSido.getSelectedItem() + " " + spinGugun.getSelectedItem()
						+ " " + spinDong.getSelectedItem());
		editor.commit();
		super.dismiss();
	}

	private String getFileName(int pos) {
		switch (pos) {
		case 0:
			return "kma/seoul.xml";
		case 1:
			return "kma/busan.xml";
		case 2:
			return "kma/gwangju.xml";
		case 3:
			return "kma/ulsan.xml";
		case 4:
			return "kma/incheon.xml";
		case 5:
			return "kma/daejun.xml";
		case 6:
			return "kma/daegu.xml";
		case 7:
			return "kma/geounggi.xml";
		case 8:
			return "kma/kangwon.xml";
		case 9:
			return "kma/geoungbook.xml";
		case 10:
			return "kma/geoungnam.xml";
		case 11:
			return "kma/chungbook.xml";
		case 12:
			return "kma/chungnam.xml";
		case 13:
			return "kma/jeonbuk.xml";
		case 14:
			return "kma/jeonnam.xml";
		case 15:
			return "kma/jeju.xml";
		default:
			Toast.makeText(context, R.string.toast_notfound_address, 4).show();
			break;
		}
		return null;
	}

	private KeyListener keyListener = new KeyListener() {

		@Override
		public boolean onKeyUp(View view, Editable text, int keyCode,
				KeyEvent event) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean onKeyOther(View view, Editable text, KeyEvent event) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean onKeyDown(View view, Editable text, int keyCode,
				KeyEvent event) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onKeyDown: " + keyCode);
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				dismiss();
				return true;
			}
			return false;
		}

		@Override
		public int getInputType() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public void clearMetaKeyState(View view, Editable content, int states) {
			// TODO Auto-generated method stub

		}
	};
}
